package com.dongdongshop.service.impl;

import com.dongdongshop.service.*;
import com.dongdongshop.utils.Comment;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Service
public class ItemPageServiceImpl implements ItemPageService {

    @Value("${itemPage.outPath}")
    private String outPath;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @DubboReference
    private GoodsService goodsService;

    @DubboReference
    private GoodsDescService goodsDescService;

    @DubboReference
    private TbItemService tbItemService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void createPage(Long id) {
        // 第一步 : 创建一个configuration对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        FileWriter fileWriter = null;
        try {
            // 第四步 : 加载一个模板,创建一个模板对象
            Template template = configuration.getTemplate("item.ftl");
            // 第五步 : 创建一个模板使用的数据集,可以是pojo也可以是map,一般是map
            HashMap<String, Object> map = new HashMap<>();
            Query query = new Query(Criteria.where("id").is(id));


            //查询商品和商品详情信息
            map.put("goods",goodsService.getGoodsById(id));
            map.put("goodsDesc",goodsDescService.getGoodsDescById(id));
            map.put("itemList",tbItemService.getItemListById(id));
            map.put("evaluateList",mongoTemplate.find(new Query(),Comment.class));
            // 商品评价查询
            List<Comment> all = mongoTemplate.find(new Query(), Comment.class);
            map.put("comments", all);
            mongoTemplate.find(query,Comment.class).forEach(System.out::println);

            // 第六步 : 创建一个Writer对象, 一般创建FileWriter对象,指定生成的文件名
            fileWriter = new FileWriter(outPath + id +".html");
            //第七步 : 调用模板对象的 process 方法输出文件
            template.process(map, fileWriter);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 第八步 : 关闭资源
            if (fileWriter != null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
